/**
 * There are code generation
 */
package com.neusoft.lohas.modules.ivm.service.purchase;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.persistence.Parameter;
import com.neusoft.lohas.common.service.BaseService;
import com.neusoft.lohas.common.utils.DateUtils;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.modules.ivm.dao.purchase.PurchaseDao;
import com.neusoft.lohas.modules.ivm.entity.purchase.Purchase;
import com.neusoft.lohas.modules.ivm.entity.purchase.PurchaseDetailItem;

/**
 * 采购指令Service
 * @author Jackie.Liu
 * @version 2014-10-30
 */
@Component
@Transactional(readOnly = true)
public class PurchaseService extends BaseService {

	@Autowired
	private PurchaseDao purchaseDao;
	
	public Purchase get(String id) {
		return purchaseDao.get(id);
	}
	
	public Page<Purchase> find(Page<Purchase> page, Purchase purchase, String hopeDate, String searchParam) {
		DetachedCriteria dc = purchaseDao.createDetachedCriteria();
		if(StringUtils.isNotBlank(hopeDate)){
			dc.add(Restrictions.gt("createDate", DateUtils.getDateStart(DateUtils.parseDate(hopeDate))));
			dc.add(Restrictions.lt("createDate", DateUtils.getDateEnd(DateUtils.parseDate(hopeDate))));
		}
		if(StringUtils.isNotBlank(purchase.getState())){
			dc.add(Restrictions.eq("state", purchase.getState()));
		}
		if (StringUtils.isNotEmpty(searchParam)){
			dc.createAlias("member", "member");
			dc.add(Restrictions.or(
				Restrictions.or(
					Restrictions.like("code", "%"+searchParam+"%")
				),
				Restrictions.or(
					Restrictions.like("member.name", "%"+searchParam+"%")
				),
				Restrictions.or(
					Restrictions.like("member.phone", "%"+searchParam+"%")
				)
			));
		}
		dc.add(Restrictions.eq(Purchase.FIELD_DEL_FLAG, Purchase.DEL_FLAG_NORMAL));
		dc.add(Restrictions.eq("merchant.id", purchase.getMerchant().getId()));
		dc.addOrder(Order.desc("createDate"));
		return purchaseDao.find(page, dc);
	}
	
	@Transactional(readOnly = false)
	public void save(Purchase purchase) {
		purchaseDao.save(purchase);
	}
	
	@Transactional(readOnly = false)
	public void delete(String id) {
		purchaseDao.deleteById(id);
	}

	/**
	 * 获取当日采购清单总数
	 * @return
	 */
	public int getOrderNumsByDate(String merchantId) {
		return purchaseDao.getOrderNumsByDate(merchantId);
	}
	
}
